package hooks

import (
	"context"
	"fmt"
	"testing"
	"time"

	"atomgit.com/atomgit_dev/git-hooks/pkg/config"
	pb "atomgit.com/atomgit_dev/satellite-proto/go"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	log "atomgit.com/atomgit_dev/alog/alogcore"
)

const (
	repoIDSuccess = 88084
	repoIDError   = 80000
)

func (s *mockServer) PreAutoGCHook(ctx context.Context, in *pb.PreAutoGCHookRequest) (*pb.PreAutoGCHookResponse, error) {
	log.Info(ctx, "PreAutoGCHook")

	switch in.GetRepository().GlRepositoryId {
	case repoIDError:
		return nil, status.Errorf(codes.ResourceExhausted, "resource exhausted")
	case repoIDSuccess:
		return &pb.PreAutoGCHookResponse{}, nil
	default:
		return nil, status.Errorf(codes.Aborted, "aborted")
	}
}

func TestPreAutoGC(t *testing.T) {
	server, _ := startTestServices(t)
	defer server.Stop()

	// grpc server listen port
	config.Load(config.Config{
		ServerEndPoint:    "localhost",
		ServerPort:        58089,
		PreReceiveTimeout: time.Second * 5,
	})

	tcs := []struct {
		name       string
		repoID     int64
		expectErr  error
		expectCode int
	}{
		{
			name:       "pre-auto-gc should always return code 1",
			repoID:     repoIDSuccess,
			expectCode: 1,
		},
		{
			name:       "pre-auto-gc error",
			repoID:     repoIDError,
			expectCode: 1,
			expectErr:  fmt.Errorf("fail to run pre-auto-gc hook: rpc error: code = ResourceExhausted desc = resource exhausted"),
		},
	}

	for _, ts := range tcs {
		t.Run(ts.name, func(t *testing.T) {
			// must set env: AGIT_PROTO_REPOSITORY
			addPbRepositoryToEnv(&pb.Repository{GlRepositoryId: ts.repoID})

			returnCode, err := preAutoGC(context.Background())
			if err != nil {
				require.EqualError(t, ts.expectErr, err.Error())
			}

			require.Equal(t, ts.expectCode, returnCode)
		})
	}
}
